﻿using System;
using System.Net.Http;
using iTeamyou.LTS.Core.Models;
using iTeamyou.LTS.Core.Services;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace iTeamyou.LTS.Core.Services
{
    public class EKPLoginService : ILoginService<LoginUser>
    {
        private SharedService sharedService;
        private HttpClient httpClient;
        public SSODBContext _dbContext;

        public EKPLoginService(SSODBContext dbContext)
        {
            _dbContext = dbContext;
            sharedService = new SharedService();
            httpClient = new HttpClient()
            {
                BaseAddress = new Uri(sharedService.GetConfig("EKPRestBaseURL"))
            };
        }

        public LoginUser Login(string app, string token)
        {
            var loginUser = new LoginUser();
            List<KeyValuePair<string, string>> kvpsList = new()
            {
                new KeyValuePair<string, string>("token", token)
            };
            var formContent = new FormUrlEncodedContent(kvpsList);
            var response = httpClient.PostAsync(sharedService.GetConfig("EKPRestLoginPath"), formContent).Result;
            var loginResult = JsonConvert.DeserializeObject<EKPLoginResponse>(response.Content.ReadAsStringAsync().Result);

            if (loginResult.result)
            {
                var result = _dbContext.LoginUsers.Where(u => u.Id == loginResult.loginName && u.AppCode == app).FirstOrDefault();
                if (result != null)
                    loginUser = result;

                if (string.IsNullOrEmpty(loginUser.Id))
                    loginUser.Id = loginResult.loginName;

                return loginUser;
            }
            return null;
        }
    }
}

